package leetcode.median;

/**
 * ClassName: $130_Solve
 * Description:
 * date: 2021-12-18 21:15
 *
 * @author liyifan
 */
public class $130_Solve {

    boolean[][] visited;

    int m;

    int n;

    public void solve(char[][] board) {
        if (board.length == 0)
            return;
        m = board.length;
        n = board[0].length;
        visited = new boolean[m][n];
        for (int i = 0;i < n;i++) {
            dfs(board, 0, i);
        }

        for (int i = 0;i < n;i++) {
            dfs(board, m - 1, i);
        }

        for (int j = 1;j < m - 1;j++) {
            dfs(board, j, 0);
        }

        for(int j = 1;j < m - 1;j++) {
            dfs(board, j, n - 1);
        }

        for (int i = 1;i < m;i++) {
            for (int j = 1;j < n;j++) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
            }
        }

        for (int i = 0;i < m;i++) {
            for (int j = 0;j < n;j++) {
                if (board[i][j] == '#') {
                    board[i][j] = 'O';
                }
            }
        }
    }

    public void dfs(char[][] board, int i, int j) {
        if (i < 0 || j < 0 || i >= m || j >= n)
            return;
//        System.out.println("i: " + i + " j:" + j + " " + board[i][j]);
        if (visited[i][j])
            return;

        visited[i][j] = true;
        if (board[i][j] == 'O') {
            board[i][j] = '#';
            dfs(board, i - 1, j);
            dfs(board, i + 1 ,j);
            dfs(board, i, j - 1);
            dfs(board, i, j + 1);
        }
    }
}
